package com.seeyon.apps.ssoAndDoc.controller;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.ssoAndDoc.utils.FilePathUtil;
import com.seeyon.apps.ssoAndDoc.utils.WdToPdfUtil;
import com.seeyon.apps.ssoAndDoc.utils.ZipUtils;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.service.CAP4FormManagerImpl;
import com.seeyon.cap4.template.bean.FormCaptureParamBean;
import com.seeyon.ctp.cap.api.manager.CAPFormManagerImpl;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.common.web.filter.RestAuthenticator;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.FileUtil;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.v3x.edoc.domain.EdocSummary;
import com.seeyon.v3x.edoc.manager.EdocSummaryManager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipOutputStream;

public class SsoAndDocController extends BaseController {

    private static final Log log = LogFactory.getLog(SsoAndDocController.class);
    private static final OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");

    public void batchDownloadEdoc(HttpServletRequest request, HttpServletResponse response){
        ColManager colManager = (ColManager) AppContext.getBean("colManager");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer =null;
        try {
            String serverName = request.getServerName();
            String serverPort = String.valueOf(request.getServerPort());
            String scheme = request.getScheme();
            String contextPath = "/seeyon";
            writer = response.getWriter();
            AffairManager affairManager = (AffairManager) AppContext.getBean("affairManager");
            EdocSummaryManager edocSummaryManager = (EdocSummaryManager) AppContext.getBean("edocSummaryManager");
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            String affairIds = request.getParameter("docId");
            String[] affairIdArray = StringUtils.split(affairIds, ",");
            String filePath = FilePathUtil.getFilePath();//工具类获取临时文件存放位置
            long uuid = UUIDLong.longUUID();
            long startTime = System.currentTimeMillis();
            String downLoadUrl = null;
            String attachUrl = null;
            StringBuilder allUrls = new StringBuilder();
            StringBuilder colDownloadUrl = new StringBuilder();
            for (int i= 0;i<affairIdArray.length;i++) {
                String affairId = affairIdArray[i];
                CtpAffair affair = affairManager.get(Long.parseLong(affairId));
                if (affair==null){
                    //是附件形式
                    FileManager fileManager  = (FileManager) AppContext.getBean("fileManager");
                    File otherfile = fileManager.getSpicFile(Long.parseLong(affairId), true);
                    V3XFile v3XFile = fileManager.getV3XFile(Long.parseLong(affairId));
                    String filename = v3XFile.getFilename();
                    String pdfPath = filePath+ uuid +File.separator+"批量文件"+File.separator+filename;
                    File pdfFile = new File(pdfPath);
                    // 确保父目录存在
                    File parentDir = pdfFile.getParentFile();
                    if (parentDir != null && !parentDir.exists()) {
                        parentDir.mkdirs(); // 创建所有必要的父目录
                    }
                    // 判断是否存在newFile
                    if (!pdfFile.exists()) {
                        pdfFile.createNewFile();
                    }
                    FileUtil.copyFile(otherfile, pdfFile);
                    attachUrl = scheme+"://"+serverName+":"+serverPort+contextPath+"/ssoAndDocControl.do?method=downLoadEdocZip&fileUrl="+uuid;
                }else {
                    Long summaryIdLong = affair.getObjectId();
                    String summaryId = summaryIdLong.toString();
                    EdocSummary summary = edocSummaryManager.getEdocSummaryById(summaryIdLong, true, true);
                    if (summary==null){
                        ColSummary colSummary = colManager.getSummaryById(Long.parseLong(summaryId));
                        if(colSummary==null){
                            log.info("下载失败");
                        }else {
                            FormCaptureParamBean bean = new FormCaptureParamBean();
                            HashMap<String, Object> colParams = new HashMap<>();
                            colParams.put("serverName",serverName);
                            colParams.put("serverPort",serverPort);
                            colParams.put("scheme",scheme);
                            colParams.put("contextPath",contextPath);
                            bean.setModuleId(colSummary.getId());
                            bean.setModuleType(1);
                            bean.setRenderType("pdf");
                            bean.setRequestParams(colParams);
                            String multiViewStr = affair.getMultiViewStr();
                            bean.setRightId(multiViewStr);
                            if (colDownloadUrl.length()>0){
                                colDownloadUrl.append(",");
                            }
                            String result = formApi4Cap4.doFormCapture(bean);
                            colDownloadUrl.append(result);
                        }
                    }else {
                        String finalPath = filePath+ uuid + File.separator +"批量文件"+File.separator+ summary.getSubject();
                        File finalPathOrder = new File(finalPath);
                        if (!finalPathOrder.exists()) {
                            finalPathOrder.mkdirs();
                        }
                        String tempPath = filePath + "temp"+File.separator + UUIDLong.longUUID();
                        File filePathOrder = new File(tempPath);
                        if (!filePathOrder.exists()) {
                            filePathOrder.mkdirs();
                        }
                        long aaa = System.currentTimeMillis();
                        Map<String, Object> params = new HashMap<>();
                        params.put("zipPath", filePath);
                        params.put("summaryTempPath", filePath);
                        params.put("attachTempPath", finalPath);
                        params.put("tempPath", tempPath);
                        params.put("summay", summary);
                        WdToPdfUtil.edocFromToSummary(params, new StringBuffer("下载文单失败"));
                        WdToPdfUtil.accessToTheBody(params, new StringBuffer("下载正文失败"));
                        WdToPdfUtil.accessToTheAttachment(params, new StringBuffer("下载附件失败"));
                        long aaaa = System.currentTimeMillis();
                        logger.info("公文转pdf时间：" + (aaaa - aaa));
                        downLoadUrl = scheme+"://"+serverName+":"+serverPort+contextPath+"/ssoAndDocControl.do?method=downLoadEdocZip&fileUrl="+uuid;
                    }
                }
            }

            if (!colDownloadUrl.toString().isEmpty()) {
                allUrls.append(colDownloadUrl);
            }
            if (attachUrl != null && !attachUrl.isEmpty()) {
                if (allUrls.length() > 0) {
                    allUrls.append(","); // 添加逗号
                }
                allUrls.append(attachUrl);
            }
            if (downLoadUrl != null && !downLoadUrl.isEmpty()&&(attachUrl==null||attachUrl.isEmpty())) {
                if (allUrls.length() > 0) {
                    allUrls.append(","); // 添加逗号
                }
                allUrls.append(downLoadUrl);
            }
            //压缩
            String summaryTempPaths = filePath+uuid+File.separator+"批量文件";
            File summaryTempOrder = new File(summaryTempPaths);
            if (!summaryTempOrder.exists()) {
                summaryTempOrder.mkdirs();
            }
            String zipFilePath = filePath+uuid+File.separator+"批量下载" + ".zip";
            File zipFile = new File(zipFilePath);
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
            FileOutputStream fileOut = new FileOutputStream(zipFilePath);
            ZipUtils.toZip(summaryTempPaths, fileOut, true);
            long endTime = System.currentTimeMillis();
            logger.info("转化时间:" + (endTime - startTime));
            //ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
            //WdToPdfUtil.zipDirectory(zipOut, summaryTempPaths, "");
            JSONObject result =  new JSONObject();
            result.put("data", downLoadUrl);
            result.put("code",200);
            result.put("colDownload",allUrls);
            writer.write(result.toString());
        } catch (Exception e) {
            logger.error("---xmc---文单转pdf下载出现异常", e);
            JSONObject result =  new JSONObject();
            result.put("code",500);
            writer.write(result.toString());
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public void downLoadEdocZip(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String zipFilePath =  request.getParameter("fileUrl");
        String filePath = FilePathUtil.getFilePath();//工具类获取临时文件存放位置
        File tempFile = new File(filePath+zipFilePath+File.separator+"批量下载"+".zip");
        InputStream  inputStream = null;
        OutputStream outputStream = null;
        if (tempFile != null && tempFile.exists() && tempFile.isFile()) {
            // 以流的形式下载文件。
            inputStream = new BufferedInputStream(new FileInputStream(tempFile));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("批量下载.zip","utf-8"));
            response.addHeader("Content-Length", "" + tempFile.length());
            response.setContentType("application/octet-stream");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
            //WdToPdfUtil.deleteDirectory(Paths.get(filePath));
        }
    }
}
